<template>
	<view class="page-container">
		<uni-ele-search :showCount="30"  :searchForm="searchForm" inline @onSearch="onSearch"></uni-ele-search>
		<view class="btns-box">
			<el-button class="btn" size="mini" type="danger" @click="downloadExcel">下载表格模板</el-button>
			<el-upload ref="uploadExcel" :action="uploadUrl" :http-request="uploadSuccess" :limit="1" :show-file-list="false" accept=".xls" class="btn upload-btn">
				上传文件
			</el-upload>
			<el-button class="btn" size="mini" type="info" @click="navToHistory">上传记录</el-button>
			<el-button class="btn" size="mini" type="primary" @click="batchDownload">批量下载</el-button>
			<el-button class="btn" size="mini"
                 type="primary"
                 @click="batchDownloadAll">导出全部数据
      </el-button>
		</view>
		<uni-ele-table :columns="columns" :data="tableData" pageable @action="handleClick" @pageChange="pageChange" @selectionChange="selectionChange"></uni-ele-table>
		<el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="visble" title="上传表单确认" width="80%">
			<uni-ele-table :columns="tmpColumns" :data="tempTableData" pageable @action="handleClick" @pageChange="pageChange"></uni-ele-table>
			<div slot="footer" class="dialog-footer"><el-button size="small" type="primary" @click="confrimSubmit">确认提交</el-button></div>
		</el-dialog>
    <el-drawer title="房源信息" direction="rtl" :visible.sync="showDrawer" size="50%" class="house-drawer">
      <house-view />
    </el-drawer>
	</view>
</template>

<script>
import { houseList, confirm, deleteById, createDownLoadTask, downLoadExcelBatchByType } from '@/common/services/house.js';
import HouseView from "../plugins/houseView";

export default {
  components: {HouseView},
  data() {
		return {
			uploadUrl: 'http://localhost:8022/house/importFile',
			visble: false,
			size: 20,
			searchData: {},
			searchForm: [
				{
					title: '小区名称',
					valueType: 'input',
					value: 'communityName'
				},
				{
					title: '合同到期后状态',
					valueType: 'select',
					value: 'contractExpireStatus',
					options: [
						{
							name: '续租',
							value: '续租'
						},
						{
							name: '腾退',
							value: '腾退'
						},
						{
							name: '空置',
							value: '空置'
						}
					]
				},
				{
					title: '承租人',
					valueType: 'input',
					value: 'name'
				},
				{
					title: '手机号',
					valueType: 'input',
					value: 'mobile'
				},
        {
          title: '开工时间',
          valueType: 'daterange',
          value: 'startTimes',
          format: 'yyyy-MM-dd HH:mm:00',
          date: true
        },
        {
          title: '竣工时间',
          valueType: 'daterange',
          value: 'endTimes',
          format: 'yyyy-MM-dd HH:mm:00',
          date: true
        }
			],
			columns: [
				{
					title: '序号',
					valueType: 'selection',
					width: 50,
					align: 'center'
				},
				{
					title: '小区名称',
					dataIndex: 'communityName',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '开工时间',
					dataIndex: 'startsTime',
					align: 'center',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					},
					render: row => {
						return this.$utils.timeFormat(row.startsTime);
					}
				},
				{
					title: '竣工时间',
					dataIndex: 'finishFilingTime',
					align: 'center',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					},
					render: row => {
						return this.$utils.timeFormat(row.finishFilingTime);
					}
				},
				{
					title: '房号',
					dataIndex: 'roomNumber',
					align: 'center',
					minWidth: 80
				},
				{
					title: '面积（㎡）',
					dataIndex: 'rent',
					align: 'center',
					minWidth: 100,
					render: row => {
						if (row.rent && row.rent.length > 0) {
							return parseFloat(row.rent).toFixed(2);
						}
						return '-';
					}
				},
				{
					title: '房屋间数',
					dataIndex: 'houseRoomNumber',
					align: 'center',
					minWidth: 80
				},
				{
					title: '承租人',
					dataIndex: 'lesseeName',
					align: 'center',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '身份证号',
					dataIndex: 'lesseeIdCard',
					minWidth: 100,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '手机号',
					dataIndex: 'lesseeMobile',
					minWidth: 100,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '居住人数',
					dataIndex: 'resideNumber',
					align: 'center',
					minWidth: 80
				},
				{
					title: '单位面积租金',
					dataIndex: 'rentAmount',
					align: 'center',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					},
					render: row => {
						return row.rentAmount + ' 元/㎡';
					}
				},
				{
					title: '合同签订时间',
					dataIndex: 'contractStartTime',
					align: 'center',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					},
					render: row => {
						return this.$utils.timeFormat(row.contractStartTime);
					}
				},
				{
					title: '合同到期时间',
					dataIndex: 'contractEndTime',
					align: 'center',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					},
					render: row => {
						return this.$utils.timeFormat(row.contractEndTime);
					}
				},
				{
					title: '合同到期后状态',
					dataIndex: 'contractExpireStatus',
					align: 'center',
					minWidth: 100,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					},
					render: row => {
						if (row.contractExpireStatus != '1') {
							return row.contractExpireStatus;
						}
						return '';
					}
				},
				{
					title: '租后管理单位',
					dataIndex: 'companyName',
					align: 'center',
					minWidth: 100,
					style: {
						display: 'initial'
					}
				},
				{
					title: '家属1',
					dataIndex: 'familyNameOne',
					minWidth: 100,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					},
					render: row => {
						return row.familyNameOne || '' + '<br/>' + row.familyIdCardOne || '';
					}
				},
				{
					title: '家属2',
					dataIndex: 'familyNameOne',
					minWidth: 100,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					},
					render: row => {
						return row.familyNameTwo || '' + '<br/>' + row.familyIdCardTwo || '';
					}
				},
				{
					title: '家属3',
					dataIndex: 'familyNameOne',
					minWidth: 100,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					},
					render: row => {
						return row.familyNameThree || '' + '<br/>' + row.familyIdCardThree || '';
					}
				},
				{
					title: '家属4',
					dataIndex: 'familyNameOne',
					minWidth: 100,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					},
					render: row => {
						return row.familyNameFour || '' + '<br/>' + row.familyIdCardFour || '';
					}
				},
				{
					title: '家属5',
					dataIndex: 'familyNameOne',
					minWidth: 100,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					},
					render: row => {
						return row.familyNameFive || '' + '<br/>' + row.familyIdCardFive || '';
					}
				},
				{
					title: '上传时间',
					dataIndex: 'createTime',
					minWidth: 100,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '备注',
					dataIndex: 'remark',
					align: 'center',
					minWidth: 150,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '操作',
					valueType: 'action',
					fixed: 'right',
					width: 80,
					actions: [
						{
							title: '删除',
							type: 'delete',
							authCode: 'house:talent:0:delete'
            },
            {
              title: '详情',
              type: 'view',
              authCode: 'house:talent:2:delete'
            }
          ]
        }
      ],
      /* table 数据 */
      tableData: {},
      tempTableData: {},
      batchNo: '',
      type: 0,
      selectedIds: [],
      tmpColumns: [],
      pageIndex: 1,
      showDrawer: false
    };
	},
	onLoad() {
		this.tmpColumns = [].concat(this.columns);
		this.tmpColumns.splice(0, 1);
		this.list();
	},
	methods: {
		downloadExcel() {
			if (this.type === 0) {
				window.open(`/download/人才房房源统计模板.xls`);
			}
			if (this.type === 1) {
				window.open(`/download/公租房房源统计模板.xls`);
			}
			if (this.type === 2) {
				window.open(`/download/保租房房源统计模板.xls`);
			}
		},
		uploadSuccess(res) {
			let self = this;
			self.batchNo = '';
			self.$utils.loading();
			uni.uploadFile({
				url: `${self.$env.base}/house/importFile/${this.type}`,
				file: res.file,
				name: 'file',
				header: {
					Authorization: uni.getStorageSync('token') || ''
				},
				success: ret => {
					self.$refs.uploadExcel.clearFiles();
					self.$utils.loading(true);
					let data = JSON.parse(ret.data);
					if (ret.statusCode == 200 && data.code === self.$env.successCode) {
						self.$utils.notify('文件[' + res.file.name + ']上传成功');
						self.batchNo = data.data;
						self.list({ batchNo: self.batchNo, confirm: 0 }, true);
					} else {
            self.$utils.notify('文件[' + res.file.name + ']上传失败!' + data.errMsg || '', 'error');
					}
				},
				fail: err => {
					self.$refs.uploadExcel.clearFiles();
					self.$utils.loading(true);
					self.$utils.notify('文件[' + res.file.name + ']上传失败', 'error');
				}
			});
		},
		confrimSubmit() {
			let self = this;
			confirm(this.batchNo, this.type).then(ret => {
				self.visble = false;
				self.$utils.notify('提交成功');
				self.list();
			});
		},
		list(params, isTemp) {
      let self = this;
      if (isTemp) {
        this.visble = true;
      }
      params = params || {};
      self.pageIndex = params.current || 1;
      houseList({
        ...params,
        type: this.type,
        size: isTemp ? 10 : this.size
      }).then(ret => {
        if (!isTemp) {
          self.tableData = ret;
        } else {
          self.tempTableData = ret;
        }
      });
    },
		navToHistory() {
			uni.navigateTo({
				url: '/house/upload/history?type=' + this.type
			});
		},
		tempPageChange(e, size) {
			this.list(
				{
					current: e,
					...this.searchData
				},
				true
			);
		},
		handleClick(data) {
			let self = this;
			switch (data.event.type) {
				case 'delete':
					this.$confirm('确定要删除这条数据吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
						deleteById(data.item.id, self.type).then(ret => {
              self.$utils.notify('操作成功');
              if (data.item.confirm) {
                self.onSearch();
              } else {
                self.list({
                  batchNo: self.batchNo,
                  confirm: 0
                }, true);
              }
            });
					});
					break;
        case 'view':
          self.showDrawer = true
          break;
			}
    },
    async batchDownload() {
      let self = this;
      if (this.selectedIds.length === 0) {
        self.$utils.notify('请选择需要下载的表格数据', 'warning');
        return;
      }
      let ret = await createDownLoadTask({ids: this.selectedIds});
      downLoadExcelBatchByType(ret, this.type);
    },
    batchDownloadAll() {
      downLoadExcelBatchByType("all", this.type);
    },
    selectionChange(e) {
      let selectedIds = [];
      e.forEach(it => {
        selectedIds.push(it.id);
      });
      this.selectedIds = selectedIds;
    },
    pageChange(e, size) {
      this.size = size || this.size;
      this.list({
				current: e,
				...this.searchData
			});
		},
		onSearch(e) {
			if (e) {
        this.searchData = e;
        if (e.startTimes && e.startTimes.length > 1) {
          this.searchData.startTime = e.startTimes[0];
          this.searchData.endTime = e.startTimes[1];
        }
        if (e.endTimes && e.endTimes.length > 1) {
          this.searchData.startTime2 = e.endTimes[0];
          this.searchData.endTime2 = e.endTimes[1];
        }
      }
			this.list({
				current: 1,
				...this.searchData
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.btns-box {
	padding: 0 16px;
	margin-bottom: -5px;
	border-radius: 5px;
	background-color: #fff;
	height: 50px;
	width: 100%;
	// border-bottom: 1px solid #ccc;
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: flex-end;

	.upload-btn {
		margin: 0 10px;
		width: 80px;
		height: 28px;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 3px;
		font-size: 12px;
		// background-color: #409eff;
		border: 1px solid #ccc;
	}
}
</style>
